package com.example.servicedemo.views;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;


import com.example.servicedemo.R;
import com.example.servicedemo.constant.Constants;
import com.example.servicedemo.event.CommendEvent;
import com.example.servicedemo.event.MessageEvent;
import com.example.servicedemo.listener.OnMessageChangeListener;
import com.example.servicedemo.service.MainService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnMessageChangeListener {

    private Button mStartButton;
    private Button mStopButton;
    private Button mLast;
    private Button mPlay;
    private Button mNext;
    private Button mBindButton;
    private Button mUnBindButton;
    private TextView mMessageView;
    private boolean mPlaying;
    private MainService mService;
    private MainServiceConnection mConnection;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            MessageEvent event = (MessageEvent) intent.getSerializableExtra("message");
            Log.d("asdf", "=====onReceive=======" + event.name + ":" + event.duration);
            mMessageView.setText("正在播放第 " + event.name + " 首歌" +
                    "\n" +
                    "剩余 " + event.duration + " 秒");
        }
    };

    Handler mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            MessageEvent event = (MessageEvent) msg.obj;
            Log.d("asdf", "=====handleMessage=======" + event.name + ":" + event.duration);
            mMessageView.setText("正在播放第 " + event.name + " 首歌" +
                    "\n" +
                    "剩余 " + event.duration + " 秒");
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        mStartButton = findViewById(R.id.start);
        mStopButton = findViewById(R.id.stop);
        mLast = findViewById(R.id.last);
        mPlay = findViewById(R.id.play);
        mNext = findViewById(R.id.next);
        mBindButton = findViewById(R.id.bind);
        mUnBindButton = findViewById(R.id.unbind);
        mMessageView = findViewById(R.id.message);
        mLast.setOnClickListener(this);
        mPlay.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mStartButton.setOnClickListener(this);
        mStopButton.setOnClickListener(this);
        mBindButton.setOnClickListener(this);
        mUnBindButton.setOnClickListener(this);
        mConnection = new MainServiceConnection();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.start) {
            Intent intent = new Intent(this, MainService.class);
            startForegroundService(intent);
        } else if (id == R.id.stop) {
            Intent intent = new Intent(this, MainService.class);
            stopService(intent);
        } else if (id == R.id.last || id == R.id.next || id == R.id.play) {
            sendCommand4(id);
        } else if (id == R.id.bind) {
            Intent intent = new Intent(this, MainService.class);
            bindService(intent, mConnection, BIND_AUTO_CREATE);
        } else if (id == R.id.unbind) {
            unbindService(mConnection);
        }
    }

    private void sendCommand(int id) {
        Intent intent = new Intent(this, MainService.class);
        String command = null;
        if (id == R.id.last) {
            command = Constants.COMMAND_LAST;
        } else if (id == R.id.next) {
            command = Constants.COMMAND_NEXT;
        } else if (id == R.id.play) {
            if (mPlaying) {
                command = Constants.COMMAND_PAUSE;
                mPlay.setText("play");
                mPlaying = false;
            } else {
                command = Constants.COMMAND_PLAY;
                mPlay.setText("pause");
                mPlaying = true;
            }
        }
        intent.putExtra("command", command);
        startService(intent);
    }

    private void sendCommand2(int id) {
        if (id == R.id.last) {
            mService.last();
        } else if (id == R.id.next) {
            mService.next();
        } else if (id == R.id.play) {
            if (mPlaying) {
                mService.pause();
                mPlay.setText("play");
                mPlaying = false;
            } else {
                mService.play();
                mPlay.setText("pause");
                mPlaying = true;
            }
        }
    }

    //EventBus方式向Service发送事件
    private void sendCommand3(int id) {
        CommendEvent event = null;
        if (id == R.id.last) {
            event = new CommendEvent(Constants.COMMAND_LAST);
        } else if (id == R.id.next) {
            event = new CommendEvent(Constants.COMMAND_NEXT);
        } else if (id == R.id.play) {
            if (mPlaying) {
                event = new CommendEvent(Constants.COMMAND_PAUSE);
                mPlay.setText("play");
                mPlaying = false;
            } else {
                event = new CommendEvent(Constants.COMMAND_PLAY);
                mPlay.setText("pause");
                mPlaying = true;
            }
        }
        EventBus.getDefault().post(event);
    }

    //使用BroadcastReceiver发送命令
    private void sendCommand4(int id) {
        String command = null;
        if (id == R.id.last) {
            command = Constants.COMMAND_LAST;
        } else if (id == R.id.next) {
            command = Constants.COMMAND_NEXT;
        } else if (id == R.id.play) {
            if (mPlaying) {
                command = Constants.COMMAND_PAUSE;
                mPlay.setText("play");
                mPlaying = false;
            } else {
                command = Constants.COMMAND_PLAY;
                mPlay.setText("pause");
                mPlaying = true;
            }
        }
        Intent intent = new Intent(Constants.ACTION_ACTIVITY_TO_SERVICE);
        intent.putExtra("command", command);
        sendBroadcast(intent);
    }

    private class MainServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("asdf", "=======onServiceConnected=======");
            MainService.MainBinder binder = (MainService.MainBinder) service;
            mService = binder.getService();
            mService.setMessageChangeListener(MainActivity.this);
            mService.setHandler(mHandler);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("asdf", "=======onServiceDisconnected=======");
            mService = null;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Log.d("asdf", "============" + event.name + ":" + event.duration);
        mMessageView.setText("正在播放第 " + event.name + " 首歌" +
                "\n" +
                "剩余 " + event.duration + " 秒");
    }

    @Override
    public void onMessageChanged(MessageEvent event) {
        Log.d("asdf", "=====onMessageChanged=======" + event.name + ":" + event.duration);
        mMessageView.setText("正在播放第 " + event.name + " 首歌" +
                "\n" +
                "剩余 " + event.duration + " 秒");
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_SERVICE_TO_ACTIVITY);
        registerReceiver(mReceiver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
        unregisterReceiver(mReceiver);
    }
}